const app = getApp();
const util = require('../../utils/util.js')
Page({

    data: {
        sum: '0.00',
        selectedNum: 0,
        imageUrl: app.globalData.imageUrl
    },
    onLoad: function(options) {
        //请求分享数据
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=get_share',
            data: {},
            method: 'GET',
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    this.setData({
                        share_default_title: res.data.datas.title,
                        share_default_image_url: res.data.datas.imageUrl
                    })
                }
            }
        })
        util.share();
        var self = this;
        wx.getStorage({
            key: 'key',
            success: res => {
                self.setData({
                    key: res.data
                })
            },
            fail: function() {
                if (app.globalData.authorized) {
                    wx.navigateTo({
                        url: "../chooselogin/chooselogin"
                    })
                } else {
                    wx.navigateTo({
                        url: "../login/login"
                    })
                }
            }
        })

    },
    onShow: function() {
        var self = this;
        wx.getStorage({
            key: 'key',
            success: res => {
                self.setData({
                    key: res.data
                })
                this.getCart();
            },
            fail: function() {
                if (app.globalData.authorized) {
                    wx.navigateTo({
                        url: "../chooselogin/chooselogin"
                    })
                } else {
                    wx.navigateTo({
                        url: "../login/login"
                    })
                }
            }
        })
    },
    // onReady: function () {
    //     this.getCart();
    // },
    getCart: function() {
        var self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_list',
            data: {
                key: self.data.key
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    if (res.data.datas.cart_count > 0) {
                        wx.setTabBarBadge({
                            index: 3,
                            text: String(res.data.datas.cart_count)
                        })
                    } else {
                        wx.removeTabBarBadge({
                            index: 3,
                        })
                    }


                    wx.setStorage({
                        key: 'cart_count',
                        data: res.data.datas.cart_count
                    })

                    self.setData({
                        cart_list: res.data.datas.cart_list,
                        sum: res.data.datas.sum
                    })
                    var selfGoods = {};
                    var storeSum = {};
                    var storeSumEach = 0;
                    var arrtemp = new Array();
                    for (let i = 0; i < 20; i++) {
                        arrtemp[i] = new Object();
                    }
                    for (let i = 0; i < self.data.cart_list.length; i++) {
                        for (let j = 0; j < self.data.cart_list[i].goods.length; j++) {
                            var goods = self.data.cart_list[i].goods[j];

                            storeSumEach += goods.goods_price * 1;
                            storeSum[self.data.cart_list[i].store_id] = storeSumEach;
                            arrtemp[i][goods.cart_id] = {
                                is_check: goods.is_check,
                                goods_num: goods.goods_num,
                                goods_price: goods.goods_price,
                                goods_name: goods.goods_name,
                            }
                        }
                        selfGoods[self.data.cart_list[i].store_id] = arrtemp[i];
                        selfGoods[self.data.cart_list[i].store_id].free_freight_price = self.data.cart_list[i].free_freight ? self.data.cart_list[i].free_freight.price.toFixed(2) : 0;
                    }
                    self.checkSlefGoods(selfGoods);
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    checkSlefGoods: function(selfGoods) {

        var sum = 0;
        var selectedNum = 0;
        var store_count = 0;
        var allgoodsSelected = true;
        for (let k in selfGoods) {
            for (let key in selfGoods[k]) {
                if (selfGoods[k][key].is_check == '0') {
                    selfGoods[k].allchecked = false;
                    break;
                } else {
                    selfGoods[k].allchecked = true;
                }
            }
        }
        for (let k in selfGoods) {
            store_count = 0
            for (let key in selfGoods[k]) {
                if (key != 'allchecked' && key != 'free_freight_price' && key != 'store_count' && key != 'dis_freight_price') {
                    if (selfGoods[k][key].is_check != '0') {
                        store_count += (parseInt(selfGoods[k][key].goods_num) * selfGoods[k][key].goods_price);
                        sum += (parseInt(selfGoods[k][key].goods_num) * selfGoods[k][key].goods_price);
                        selectedNum += (selfGoods[k][key].goods_num * 1);
                    } else {
                        selfGoods[k][key].count = 0;
                    }

                }

            }
            selfGoods[k].store_count = store_count;
            selfGoods[k].dis_freight_price = (selfGoods[k].free_freight_price - store_count).toFixed(2);
        }
        for (let k in selfGoods) {
            for (let key in selfGoods[k]) {
                if (key != 'allchecked' && key != 'free_freight_price' && key != 'store_count' && key != 'dis_freight_price') {
                    if (selfGoods[k][key].is_check == '0') {
                        allgoodsSelected = false;
                        break;
                    }

                }
            }
        }

        this.setData({
            selfGoods: selfGoods,
            sum: sum.toFixed(2),
            selectedNum: selectedNum,
            allgoodsSelected: allgoodsSelected
        })
    },
    selectStore: function(e) {
        var self = this;
        var is_check;
        var cartidStr = '';
        var store_id = e.currentTarget.dataset.store_id;

        if (e.detail.value.length == 0) {
            //全不选
            is_check = '0';
            for (let k in this.data.selfGoods[store_id]) {
                if (k != 'allchecked' && k != 'free_freight_price' && k != 'store_count' && k != 'dis_freight_price') {
                    this.data.selfGoods[store_id][k].is_check = '0'
                }
            }

            this.checkSlefGoods(this.data.selfGoods);
        } else {
            //全选
            is_check = '1';
            for (let k in this.data.selfGoods[store_id]) {
                if (k != 'allchecked' && k != 'free_freight_price' && k != 'store_count' && k != 'dis_freight_price') {
                    this.data.selfGoods[store_id][k].is_check = '1'
                }
            }
            this.checkSlefGoods(this.data.selfGoods);
        }
        for (let k in this.data.selfGoods[store_id]) {
            if (k != 'allchecked' && k != 'free_freight_price' && k != 'store_count' && k != 'dis_freight_price') {
                cartidStr += (k + ',')
            }
        }
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_check',
            data: {
                key: self.data.key,
                cart_id: cartidStr,
                is_check: is_check,
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: res => {

            }
        })
    },
    selectGoods: function(e) {
        var self = this;
        var myGoods = this.data.selfGoods;
        var is_check = '0';
        var cart_id = e.currentTarget.dataset.cart_id;
        var store_id = e.currentTarget.dataset.store_id;
        var goods_price = e.currentTarget.dataset.goods_price;
        if (e.detail.value == '') {
            //未选
            is_check = '0';
            myGoods[store_id][cart_id].is_check = is_check;
            this.setData({
                sum: (this.data.sum - myGoods[store_id][cart_id].goods_num * goods_price).toFixed(2)
            })
            this.checkSlefGoods(myGoods);
        } else {
            //选中
            is_check = '1';
            myGoods[store_id][cart_id].is_check = is_check;
            this.checkSlefGoods(myGoods);
        }
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_check',
            data: {
                key: self.data.key,
                cart_id: cart_id,
                is_check: is_check
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: res => {

            }
        })
    },
    goodsDelete: function(e) {
        var self = this;
        var cart_id = e.currentTarget.dataset.cart_id;
        wx.showModal({
            title: '温馨提示',
            content: '确定删除此商品吗？',
            success(res) {
                if (res.confirm) {
                    wx.request({
                        url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_del',
                        data: {
                            key: self.data.key,
                            cart_id: cart_id
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/x-www-form-urlencoded'
                        },
                        dataType: 'json',
                        success: (res) => {
                            if (res.data.code == 200) {
                                this.getCart();
                            } else {
                                wx.showToast({
                                    title: res.data.datas.error,
                                    icon: 'none',
                                    duration: 3000
                                })
                            }
                        }
                    });
                }
            }
        })
    },
    addCart: function(e) {
        var self = this;
        var cart_id = e.currentTarget.dataset.cart_id;
        var store_id = e.currentTarget.dataset.store_id;
        var goodsNum = this.data.selfGoods[store_id][cart_id].goods_num;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_edit_quantity',
            data: {
                key: self.data.key,
                cart_id: cart_id,
                quantity: goodsNum * 1 + 1
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: res => {
                if (res.data.code == 200) {
                    self.data.selfGoods[store_id][cart_id].goods_num = goodsNum * 1 + 1;
                    self.checkSlefGoods(self.data.selfGoods);
                    wx.getStorage({
                        key: 'cart_count',
                        success: (res) => {
                            wx.setTabBarBadge({
                                index: 3,
                                text: String(res.data + 1)
                            })
                            wx.setStorage({
                                key: 'cart_count',
                                data: parseInt(res.data + 1)
                            })
                        },
                    })

                } else {
                    wx.showToast({
                        title: res.data.datas.error,
                        icon: 'none'
                    })
                }
            }
        })
    },
    cutCart: function(e) {
        var self = this;
        var cart_id = e.currentTarget.dataset.cart_id;
        var store_id = e.currentTarget.dataset.store_id;
        var goodsNum = this.data.selfGoods[store_id][cart_id].goods_num;
        if (goodsNum == 1 || goodsNum == 0) {
            wx.showModal({
                title: '温馨提示',
                content: '确定删除此商品吗？',
                success: res => {
                    if (res.confirm) {
                        //调用删除接口
                        wx.request({
                            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_del',
                            data: {
                                key: self.data.key,
                                cart_id: cart_id
                            },
                            method: 'POST',
                            header: {
                                'content-type': 'application/x-www-form-urlencoded'
                            },
                            dataType: 'json',
                            success: res => {
                                if (res.data.code == 200) {
                                    if (goodsNum != 0) {
                                        wx.getStorage({
                                            key: 'cart_count',
                                            success: (res) => {
                                                if (res.data > 1) {
                                                    wx.setTabBarBadge({
                                                        index: 3,
                                                        text: String(res.data - 1)
                                                    })
                                                } else {
                                                    wx.removeTabBarBadge({
                                                        index: 3,
                                                    })
                                                }

                                                wx.setStorage({
                                                    key: 'cart_count',
                                                    data: res.data - 1
                                                })
                                            }
                                        })
                                    }
                                    this.getCart();
                                }
                            }
                        })
                    }
                }
            })
        } else {
            wx.request({
                url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_edit_quantity',
                data: {
                    key: self.data.key,
                    cart_id: cart_id,
                    quantity: goodsNum * 1 - 1
                },
                method: 'POST',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                dataType: 'json',
                success: res => {
                    if (res.data.code == 200 || res.data.datas.error == '超出限购数或库存不足') {
                        self.data.selfGoods[store_id][cart_id].goods_num = goodsNum * 1 - 1;
                        self.checkSlefGoods(self.data.selfGoods);
                        wx.getStorage({
                            key: 'cart_count',
                            success: (res) => {
                                if (res.data > 1) {
                                    wx.setTabBarBadge({
                                        index: 3,
                                        text: String(res.data - 1)
                                    })
                                } else {
                                    wx.removeTabBarBadge({
                                        index: 3,
                                    })
                                }

                                wx.setStorage({
                                    key: 'cart_count',
                                    data: res.data - 1
                                })
                            }
                        })
                    } else {
                        wx.showToast({
                            title: res.data.datas.error,
                            icon: 'none'
                        })
                    }
                }
            })
        }
    },
    selectAllgoods: function(e) {
        var self = this;
        var selfGoods = this.data.selfGoods;
        var cartidStr = '';
        var is_check = 0;
        for (let k in selfGoods) {
            for (let key in selfGoods[k]) {
                if (key != 'allchecked' && key != 'free_freight_price' && key != 'store_count' && key != 'dis_freight_price') {
                    cartidStr += (key + ',')
                    if (e.detail.value == '') {
                        selfGoods[k][key].is_check = '0';
                        is_check = 0;
                    } else {
                        selfGoods[k][key].is_check = '1';
                        is_check = 1;
                    }
                }
            }
        }
        this.checkSlefGoods(selfGoods);
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_check',
            data: {
                key: self.data.key,
                cart_id: cartidStr,
                is_check: is_check,
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: res => {

            }
        })
    },
    cartSubmit: function() {
        var cart_id = '';
        var selfGoods = this.data.selfGoods;
        var subTips = '';
        for (let k in selfGoods) {
            for (let key in selfGoods[k]) {
                if (key != 'allchecked' & selfGoods[k][key].is_check != 0 && key != 'free_freight_price' && key != 'store_count' && key != 'dis_freight_price') {
                    cart_id += (key + '|' + selfGoods[k][key].goods_num + ',')
                }
                if (selfGoods[k][key].is_check == 1 && selfGoods[k][key].goods_num == 0) {
                    subTips += selfGoods[k][key].goods_name + '\n';
                }
            }
        }


        if (subTips != '') {
            wx.showModal({
                content: subTips + '库存不足/已下架',
                confirmText: '确认结算',
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../confirm_order/confirm_order?ifcart=1&cart_id=' + cart_id
                        })
                    } else if (res.cancel) {}
                }
            })
        } else {
            wx.navigateTo({
                url: '../confirm_order/confirm_order?ifcart=1&cart_id=' + cart_id
            })
        }

    },
    onShareAppMessage: function() {
        let share_key = this.data.key ? this.data.key : '';
        let share_path = '';
        if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
            share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
        } else {
            share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
        }
        return {
            title: this.data.share_default_title,
            imageUrl: this.data.share_default_image_url,
            path: share_path
        }
    },
    togoodsDetail: function(e) {
        var goods_id = e.currentTarget.dataset.goods_id
        wx.navigateTo({
            url: '../goods_detail/goods_detail?goods_id=' + goods_id
        })
    }
})